package org.example.backend.demos.web.filter;

import com.alibaba.fastjson2.JSON;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.demos.web.UserModule.entity.LoginResult;
import org.example.backend.demos.web.Util.JwtTokenUtil;
import org.example.backend.demos.web.result.R;
import org.example.backend.demos.web.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.io.PrintWriter;

import static org.example.backend.demos.web.result.ResultCode.*;


@Slf4j
@Component
public class jwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String URI = request.getRequestURI();
        log.info(URI);
        if (
                URI.startsWith("/api/auth/login") ||
                        URI.startsWith("/api/auth/register") ||
                        URI.startsWith("/news/api/allnews") ||
                        URI.startsWith("/projects/api/allproject") ||
                        URI.startsWith("/projects/api/page") ||
                        URI.startsWith("/news/api/page") ||
                        URI.matches("/news/api/\\d+") ||
                        URI.matches("/projects/api/\\d+") ||
                        URI.startsWith("/api/auth/check-username") ||
                        URI.startsWith("/api/auth/check-phone")||
                        URI.startsWith("/cos/api/user/upimage") ||
                        URI.startsWith("/cos/api/user/downimage")
        ) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取token
        String accessToken = request.getHeader("token");

        if (StringUtils.isNullOrEmpty(accessToken)) {
//            failureHandler.onAuthenticationFailure(request, response, new AuthenticationException("token缺失") {
//            });
            exception(ResultCode.MISSING_TOKEN, "", response);
            return;
        }
        // 解析令牌
        ResultCode Token = jwtTokenUtil.isToken(accessToken);
        switch (Token) {
            case VALID_TOKEN:
                log.atInfo().log(Token.getMsg());
                break;
            case EXPIRED_TOKEN:
                exception(EXPIRED_TOKEN, "", response);
                return;
            case INVALID_TOKEN:
                exception(INVALID_TOKEN, "", response);
                return;
        }
        // 提取token
        String usernameFromToken = jwtTokenUtil.getUsernameFromToken(accessToken);
        Long userIdFromToken = jwtTokenUtil.getUserIdFromToken(accessToken);
        String roleFromToken = jwtTokenUtil.getRoleFromToken(accessToken);
        LoginResult myUserDetails = LoginResult.builder().id(userIdFromToken).role(roleFromToken).username(usernameFromToken).build();
        // 安全上下文
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(myUserDetails, null, null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);

    }

    public void exception(ResultCode resultCode, String data, HttpServletResponse response) throws IOException {
        R<Object> result = new R<>();
        result.setCode(resultCode.getCode());
        result.setMsg(resultCode.getMsg());
        result.setData(data);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String json = JSON.toJSONString(result);
        printWriter.println(json);
        log.atError().log(resultCode.getMsg());
    }
}
